<template>
  <div class="bg-gray-50 min-h-screen">
    <!-- 页面标题 -->
    <div class="bg-white border-b border-gray-200 shadow-sm">
      <div class="container mx-auto px-4 py-5">
        <h1 class="text-2xl font-bold text-gray-800">AI图片生成</h1>
        <p class="text-gray-500 mt-1">通过文字描述让AI生成高质量图片，支持多种风格和尺寸</p>
      </div>
    </div>
    
    <!-- 主内容区 -->
    <div class="container mx-auto px-4 py-6">
      <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <!-- 左侧：参数设置 -->
        <div class="lg:col-span-1">
          <div class="bg-white rounded-lg shadow-sm p-5 sticky top-4">
            <h2 class="text-lg font-medium text-gray-800 mb-4">生成参数</h2>
            
            <div class="space-y-4">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">图片描述</label>
                <textarea
                  v-model="form.prompt"
                  class="form-input w-full min-h-[120px]"
                  placeholder="详细描述您想要生成的图片内容..."
                ></textarea>
                <p class="text-xs text-gray-500 mt-1">
                  示例：一只穿着太空服的猫在月球上跳跃，背景是地球和星星，超现实主义风格
                </p>
              </div>
              
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">艺术风格</label>
                <select
                  v-model="form.style"
                  class="form-input w-full"
                >
                  <option value="photorealistic">照片写实</option>
                  <option value="cartoon">卡通动漫</option>
                  <option value="digital-art">数字艺术</option>
                  <option value="oil-painting">油画风格</option>
                  <option value="watercolor">水彩风格</option>
                  <option value="sketch">素描风格</option>
                  <option value="abstract">抽象风格</option>
                  <option value="surrealism">超现实主义</option>
                </select>
              </div>
              
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">图片尺寸</label>
                <div class="grid grid-cols-3 gap-2">
                  <button
                    class="py-2 border rounded-md text-sm"
                    :class="form.aspect === 'square' ? 'bg-primary text-white border-primary' : 'border-gray-300 hover:bg-gray-50'"
                    @click="form.aspect = 'square'"
                  >
                    正方形
                  </button>
                  <button
                    class="py-2 border rounded-md text-sm"
                    :class="form.aspect === 'portrait' ? 'bg-primary text-white border-primary' : 'border-gray-300 hover:bg-gray-50'"
                    @click="form.aspect = 'portrait'"
                  >
                    竖版
                  </button>
                  <button
                    class="py-2 border rounded-md text-sm"
                    :class="form.aspect === 'landscape' ? 'bg-primary text-white border-primary' : 'border-gray-300 hover:bg-gray-50'"
                    @click="form.aspect = 'landscape'"
                  >
                    横版
                  </button>
                </div>
              </div>
              
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">生成数量</label>
                <select
                  v-model="form.count"
                  class="form-input w-full"
                >
                  <option value="1">1张</option>
                  <option value="2" selected>2张</option>
                  <option value="4">4张</option>
                  <option value="8">8张</option>
                </select>
              </div>
              
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">创意度</label>
                <div class="flex items-center">
                  <input
                    type="range"
                    v-model="form.creativity"
                    min="0"
                    max="100"
                    class="w-full"
                  >
                  <span class="ml-2 text-sm w-10 text-center">{{ form.creativity }}%</span>
                </div>
                <div class="flex justify-between text-xs text-gray-500 mt-1">
                  <span>忠实于描述</span>
                  <span>更具创意性</span>
                </div>
              </div>
              
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">负面描述（可选）</label>
                <input
                  type="text"
                  v-model="form.negativePrompt"
                  class="form-input w-full"
                  placeholder="描述您不想要的元素，用逗号分隔"
                >
                <p class="text-xs text-gray-500 mt-1">例如：模糊, 低质量, 水印, 文字</p>
              </div>
              
              <div class="pt-2">
                <button
                  class="btn btn-primary w-full flex items-center justify-center"
                  :disabled="loading || !form.prompt"
                  @click="generateImages"
                >
                  <i v-if="loading" class="fa fa-spinner fa-spin mr-2"></i>
                  <span>生成图片</span>
                </button>
                <button
                  class="btn btn-secondary w-full mt-3"
                  @click="clearForm"
                >
                  重置参数
                </button>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 右侧：生成结果 -->
        <div class="lg:col-span-2">
          <div class="bg-white rounded-lg shadow-sm overflow-hidden">
            <!-- 结果工具栏 -->
            <div class="bg-gray-50 px-5 py-3 border-b border-gray-200 flex flex-wrap items-center justify-between gap-3">
              <h2 class="text-lg font-medium text-gray-800">生成结果</h2>
              
              <div class="flex gap-2">
                <button
                  class="btn btn-secondary flex items-center"
                  :disabled="!generatedImages.length"
                  @click="downloadAllImages"
                >
                  <i class="fa fa-download mr-1"></i>下载全部
                </button>
                <button
                  class="btn btn-primary flex items-center"
                  :disabled="!generatedImages.length || loading"
                  @click="regenerateImages"
                >
                  <i v-if="loading" class="fa fa-spinner fa-spin mr-1"></i>
                  <i v-else class="fa fa-refresh mr-1"></i>
                  重新生成
                </button>
              </div>
            </div>
            
            <!-- 结果内容区 -->
            <div class="p-5">
              <!-- 空状态 -->
              <div v-if="!generatedImages.length && !loading" class="py-16 text-center">
                <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-gray-100 mb-4">
                  <i class="fa fa-picture-o text-2xl text-gray-400"></i>
                </div>
                <h3 class="text-lg font-medium mb-2">尚未生成图片</h3>
                <p class="text-gray-500 max-w-md mx-auto">
                  输入详细的图片描述并设置参数，AI将为您生成符合要求的图片
                </p>
              </div>
              
              <!-- 加载状态 -->
              <div v-if="loading" class="py-16 text-center">
                <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-gray-100 mb-4">
                  <i class="fa fa-spinner fa-spin text-2xl text-primary"></i>
                </div>
                <h3 class="text-lg font-medium mb-2">AI正在生成图片</h3>
                <p class="text-gray-500 max-w-md mx-auto">
                  图片生成需要一定时间，请耐心等待...
                </p>
              </div>
              
              <!-- 生成结果 -->
              <div v-if="generatedImages.length && !loading">
                <div class="flex items-center text-sm text-gray-500 mb-6">
                  <span><i class="fa fa-clock-o mr-1"></i> 生成时间: {{ generateTime }}</span>
                  <span class="mx-3">|</span>
                  <span><i class="fa fa-picture-o mr-1"></i> 共 {{ generatedImages.length }} 张图片</span>
                </div>
                
                <!-- 图片网格 -->
                <div class="grid grid-cols-1 sm:grid-cols-2 gap-6">
                  <div 
                    v-for="(image, index) in generatedImages" 
                    :key="index"
                    class="relative group"
                  >
                    <div class="bg-gray-100 rounded-lg overflow-hidden aspect-square sm:aspect-auto" 
                         :style="imageStyle">
                      <img 
                        :src="image.url" 
                        alt="AI生成图片" 
                        class="w-full h-full object-cover"
                      >
                    </div>
                    
                    <!-- 悬停操作按钮 -->
                    <div class="absolute inset-0 bg-black bg-opacity-0 group-hover:bg-opacity-30 transition-colors flex items-center justify-center opacity-0 group-hover:opacity-100">
                      <div class="flex gap-2">
                        <button 
                          class="w-10 h-10 rounded-full bg-white flex items-center justify-center text-gray-700 hover:text-primary"
                          @click.stop="viewImage(image)"
                          title="查看大图"
                        >
                          <i class="fa fa-search-plus"></i>
                        </button>
                        <button 
                          class="w-10 h-10 rounded-full bg-white flex items-center justify-center text-gray-700 hover:text-primary"
                          @click.stop="downloadImage(image, index)"
                          title="下载图片"
                        >
                          <i class="fa fa-download"></i>
                        </button>
                        <button 
                          class="w-10 h-10 rounded-full bg-white flex items-center justify-center text-gray-700 hover:text-primary"
                          @click.stop="variationImage(image, index)"
                          title="生成变体"
                        >
                          <i class="fa fa-random"></i>
                        </button>
                      </div>
                    </div>
                  </div>
                </div>
                
                <!-- 提示信息 -->
                <div class="mt-8 p-4 bg-blue-50 border border-blue-100 rounded-lg">
                  <h3 class="font-medium text-blue-800 mb-2 flex items-center">
                    <i class="fa fa-lightbulb-o mr-2"></i>优化提示
                  </h3>
                  <ul class="list-disc pl-5 text-sm text-blue-700 space-y-1">
                    <li>描述越详细，生成结果越符合预期</li>
                    <li>可以指定具体的艺术家风格、光照效果或构图方式</li>
                    <li>如需修改，可基于当前结果生成变体或调整描述词重新生成</li>
                    <li>高创意度可能产生惊喜效果，但也可能偏离原始描述</li>
                  </ul>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 历史记录 -->
          <div class="bg-white rounded-lg shadow-sm mt-6">
            <div class="px-5 py-3 border-b border-gray-200">
              <h2 class="text-lg font-medium text-gray-800">生成历史</h2>
            </div>
            <div class="p-4">
              <div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3">
                <div 
                  v-for="(history, historyIndex) in generateHistory" 
                  :key="historyIndex"
                  class="group relative cursor-pointer"
                >
                  <div class="aspect-square bg-gray-100 rounded overflow-hidden border border-gray-200">
                    <img 
                      :src="history.images[0].url" 
                      alt="历史图片" 
                      class="w-full h-full object-cover"
                    >
                  </div>
                  <div class="absolute inset-0 bg-black bg-opacity-0 group-hover:bg-opacity-50 transition-colors flex items-center justify-center opacity-0 group-hover:opacity-100">
                    <button 
                      class="w-8 h-8 rounded-full bg-white flex items-center justify-center text-gray-700"
                      @click.stop="loadHistory(history)"
                    >
                      <i class="fa fa-eye"></i>
                    </button>
                  </div>
                </div>
              </div>
              
              <div v-if="generateHistory.length === 0" class="py-8 text-center text-gray-500 text-sm">
                暂无生成历史
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 图片预览弹窗 -->
    <div 
      v-if="previewImageUrl"
      class="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-80 p-4"
      @click="closePreview"
    >
      <div class="relative max-w-4xl w-full" @click.stop>
        <button 
          class="absolute -top-12 right-0 text-white text-2xl hover:text-gray-300"
          @click="closePreview"
        >
          <i class="fa fa-times"></i>
        </button>
        <img 
          :src="previewImageUrl" 
          alt="图片预览" 
          class="max-w-full max-h-[80vh] object-contain"
        >
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { formatDate } from '@/utils/date'

// 表单数据
const form = ref({
  prompt: '',
  style: 'photorealistic',
  aspect: 'square',
  count: '2',
  creativity: 50,
  negativePrompt: ''
})

// 生成状态
const loading = ref(false)
const generatedImages = ref([])
const generateTime = ref('')
const generateHistory = ref([])
const previewImageUrl = ref('')

// 图片样式计算
const imageStyle = computed(() => {
  if (form.value.aspect === 'square') {
    return { aspectRatio: '1 / 1' }
  } else if (form.value.aspect === 'portrait') {
    return { aspectRatio: '2 / 3' }
  } else {
    return { aspectRatio: '3 / 2' }
  }
})

// 生成图片
const generateImages = async () => {
  if (!form.value.prompt) return
  
  loading.value = true
  try {
    // 模拟AI生成过程
    await new Promise(resolve => setTimeout(resolve, 3000))
    
    const count = parseInt(form.value.count)
    const result = []
    
    // 生成图片URL（实际项目中替换为真实的AI生成图片URL）
    for (let i = 0; i < count; i++) {
      // 根据不同风格生成不同的图片ID范围
      let startId = 20
      switch (form.value.style) {
        case 'cartoon':
          startId = 100
          break
        case 'digital-art':
          startId = 200
          break
        case 'oil-painting':
          startId = 300
          break
        case 'watercolor':
          startId = 400
          break
        case 'sketch':
          startId = 500
          break
        case 'abstract':
          startId = 600
          break
        case 'surrealism':
          startId = 700
          break
        default:
          startId = 20
      }
      
      // 根据比例设置不同尺寸
      let width = 600, height = 600
      if (form.value.aspect === 'portrait') {
        width = 400
        height = 600
      } else if (form.value.aspect === 'landscape') {
        width = 600
        height = 400
      }
      
      result.push({
        url: `https://picsum.photos/id/${startId + i}/600/600`,
        width,
        height,
        style: form.value.style
      })
    }
    
    // 更新结果
    generatedImages.value = result
    generateTime.value = new Date().toLocaleString()
    
    // 保存到历史记录
    saveToHistory()
    
  } catch (error) {
    console.error('生成图片失败:', error)
  } finally {
    loading.value = false
  }
}

// 重新生成图片
const regenerateImages = () => {
  generateImages()
}

// 生成变体图片
const variationImage = async (originalImage, index) => {
  loading.value = true
  try {
    // 模拟生成变体
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    // 保持尺寸和风格不变，生成新图片
    const newImage = {
      ...originalImage,
      url: `https://picsum.photos/id/${Math.floor(Math.random() * 100) + 800}/600/600`
    }
    
    // 替换当前位置的图片
    generatedImages.value.splice(index, 1, newImage)
    
  } catch (error) {
    console.error('生成变体图片失败:', error)
  } finally {
    loading.value = false
  }
}

// 查看大图
const viewImage = (image) => {
  previewImageUrl.value = image.url
}

// 关闭预览
const closePreview = () => {
  previewImageUrl.value = ''
}

// 下载单张图片
const downloadImage = (image, index) => {
  const link = document.createElement('a')
  link.href = image.url
  link.download = `ai-generated-${Date.now()}-${index + 1}.jpg`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// 下载全部图片
const downloadAllImages = () => {
  generatedImages.value.forEach((image, index) => {
    setTimeout(() => {
      downloadImage(image, index)
    }, index * 300) // 错开下载时间，避免浏览器限制
  })
}

// 保存到历史记录
const saveToHistory = () => {
  const historyItem = {
    prompt: form.value.prompt,
    images: generatedImages.value,
    timestamp: new Date().getTime(),
    params: { ...form.value }
  }
  
  generateHistory.value.unshift(historyItem)
  
  // 限制历史记录数量
  if (generateHistory.value.length > 12) {
    generateHistory.value.pop()
  }
}

// 加载历史记录
const loadHistory = (history) => {
  generatedImages.value = history.images
  generateTime.value = new Date(history.timestamp).toLocaleString()
  form.value = { ...history.params }
}

// 格式化历史时间
const formatHistoryTime = (timestamp) => {
  return formatDate(new Date(timestamp), 'yyyy-MM-dd HH:mm')
}

// 清空表单
const clearForm = () => {
  form.value = {
    prompt: '',
    style: 'photorealistic',
    aspect: 'square',
    count: '2',
    creativity: 50,
    negativePrompt: ''
  }
  generatedImages.value = []
}
</script>
